package com.sdp.right.cron;


import java.time.LocalDateTime;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.sdp.core.bizc.actor.SysActorConfig;
import com.sdp.core.bizc.utils.ApplicationContextUtils;
import com.sdp.right.entity.SysCron;
import com.sdp.right.entity.SysCronLog;
import com.sdp.right.utils.RightConstants;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;




@Service
public interface ScheduledOfTask extends Runnable{
	

	/**
     * 定时任务方法
     */
    void execute();
    /**
     * 实现控制定时任务启用或禁用的功能
     */
    @Override
    default void run() {
    	SysCron cron = TaskCollection.getTask(this.getClass().getName());
        if (RightConstants.否.getCode().equals(cron.getIsUse())) {
            // 任务是禁用状态
            return;
        }
        //是否生成日志
        if(StringUtils.isEmpty(cron.getIsCreateLog()) || RightConstants.否.getCode().equals(cron.getIsCreateLog())) {
        	execute();
        	return;
        }
        SysCronLog log = null;
        String strFix=".systemTask.actor";
        try {
        	log = new SysCronLog();
        	log.setBeginTime(LocalDateTime.now());
        	log.setSystemNo(cron.getSystemNo());
        	log.setTaskName(cron.getTaskName());
        	execute();
        	log.setEndTime(LocalDateTime.now());
        	log.setTaskState("成功");
		} catch (Exception e) {
			e.printStackTrace();
			log.setEndTime(LocalDateTime.now());
			log.setTaskState("失败");
			log.setTaskException(stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace()));
		}finally {
			Map<String,ActorRef> sysActorMap = ApplicationContextUtils.getBean(SysActorConfig.class).getSysActorMap();
			ActorSystem actorSystem = ApplicationContextUtils.getBean(SysActorConfig.class).getSysActorSystem();
			ActorRef actor = sysActorMap.get(cron.getTaskClass()+strFix);
		
			if(actor==null) {
				actor = actorSystem.actorOf(Props.create(TaskLogActor.class), cron.getTaskClass()+strFix);
				sysActorMap.put(cron.getTaskClass()+strFix, actor);
			}
			actor.tell(log, ActorRef.noSender());
		}
    }
    
    default String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
		StringBuffer strbuff = new StringBuffer();
		for (StackTraceElement stet : elements) {
			strbuff.append(stet + "\n");
		}
		String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
		return message;
	}
    	 
}
